import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:nft_shop/my/model/models.dart';
import 'package:nft_shop/my/page/order/my_order_details_page.dart';
import 'package:nft_shop/net/dio_api.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/my_button.dart';
import 'package:tobias/tobias.dart' as tobias;
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:url_launcher/url_launcher.dart';

class MyOrderItem extends StatefulWidget {
  OrderListModel model;
  VoidCallback onPressed;

  MyOrderItem({Key? key, required this.model, required this.onPressed})
      : super(key: key);

  @override
  _MyOrderItemState createState() => _MyOrderItemState();
}

class _MyOrderItemState extends State<MyOrderItem> {
  late TimerUtil _timerUtil;
  late int endtime = 0;
  ConfigNameDetail? article;
  ConfigNameDetail? alArticle;
  StreamSubscription? testSubscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getConfigNameDetailAli("alipay_is_open");
    getConfigNameDetail("wechatpay_is_open");
    if (widget.model.status == 1) {
      endtime = widget.model.endTime!;
      _timerUtil = new TimerUtil(mTotalTime: endtime * 1000);
      _timerUtil.setOnTimerTickCallback((int tick) {
        setState(() {
          endtime -= 1;
          widget.model.endTime = endtime;
        });
        if (endtime == 0) {
          _timerUtil.cancel();
          //跳转主页面
          widget.onPressed();
        }
      });
      // //开始倒计时
      _timerUtil.startCountDown();
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    try {
      _timerUtil.cancel();
      testSubscription?.cancel();
    } catch (e) {}
  }

  @override
  Widget build(BuildContext context) {
    //状态 1待付款 2(买)已完成 3代卖中 4(卖)已完成 5订单已超时 6已取消
    if (widget.model.status == 1) {
      return _waitPaymentWidget(widget.model);
    } else if (widget.model.status == 2 || widget.model.status == 4) {
      return _orderCompleteWidget(widget.model);
    } else if (widget.model.status == 5) {
      return _orderCancelWidget(widget.model, "已超时");
    } else if (widget.model.status == 6) {
      return _orderCancelWidget(widget.model, "已取消");
    } else {
      return Container();
    }
  }

  ///待付款
  Widget _waitPaymentWidget(OrderListModel model) {
    return InkWell(
      onTap: () => Get.to(MyOrderDetailsPage(model: model)),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 13),
        decoration: BoxDecoration(
            border: Border(
          top: Divider.createBorderSide(context, width: 10),
        )),
        child: Column(
          children: [
            ///订单号
            orderNumTopWidget(num: model.ordersn ?? "", state: "待付款"),
            SizedBox(
              height: 15,
            ),

            ///订单信息
            model.goodsOrderType == 1
                ? orderInfoBuyWidget(
                    image: model.thumb ?? "",
                    title: model.goodsTitle ?? "",
                    type: model.nickname ?? "",
                    price: model.goodsOrderType == 1
                        ? model.buyersPrice ?? ""
                        : model.sellerPrice ?? "")
                : orderInfoSellWidget(
                    image: model.thumb ?? "",
                    id: model.buyersMemberCode ?? "",
                    title: model.goodsTitle ?? "",
                    type: model.nickname ?? "",
                    buyPrice: model.buyersPrice ?? "",
                    sellPrice: model.sellerPrice ?? ""),
            SizedBox(
              height: 12,
            ),

            ///订单价格
            orderPriceWidget(
                time: model.placeTime ?? "",
                prcie: model.goodsOrderType == 1
                    ? model.buyersPrice ?? ""
                    : model.sellerPrice ?? "",
                goodsOrderType: model.goodsOrderType!),
            SizedBox(
              height: 11,
            ),
            orderCountdownWidget("请在 ${_durationTransform(endtime)}秒内付款"),
            SizedBox(
              height: 10,
            ),
            orderPaymentWidget(),
          ],
        ),
      ),
    );
  }

  ///已完成
  Widget _orderCompleteWidget(OrderListModel model) {
    return InkWell(
      onTap: () => Get.to(MyOrderDetailsPage(model: model)),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 13),
        decoration: BoxDecoration(
            border: Border(
          top: Divider.createBorderSide(context, width: 10),
        )),
        child: Column(
          children: [
            ///订单号
            orderNumTopWidget(num: model.ordersn ?? "", state: "已完成"),
            SizedBox(
              height: 15,
            ),

            ///订单信息
            model.goodsOrderType == 1
                ? orderInfoBuyWidget(
                    image: model.thumb ?? "",
                    title: model.goodsTitle ?? "",
                    type: model.nickname ?? "",
                    price: model.goodsOrderType == 1
                        ? model.buyersPrice ?? ""
                        : model.sellerPrice ?? "")
                : orderInfoSellWidget(
                    image: model.thumb ?? "",
                    id: model.buyersMemberCode ?? "",
                    title: model.goodsTitle ?? "",
                    type: model.nickname ?? "",
                    buyPrice: model.buyersPrice ?? "",
                    sellPrice: model.sellerPrice ?? ""),
            SizedBox(
              height: 12,
            ),

            ///订单价格
            orderPriceWidget(
                time: model.placeTime ?? "",
                prcie: model.goodsOrderType == 1
                    ? model.buyersPrice ?? ""
                    : model.sellerPrice ?? "",
                goodsOrderType: model.goodsOrderType!),
          ],
        ),
      ),
    );
  }

  ///已取消
  Widget _orderCancelWidget(OrderListModel model, String state) {
    return InkWell(
      onTap: () => Get.to(MyOrderDetailsPage(model: model)),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 13),
        decoration: BoxDecoration(
            border: Border(
          top: Divider.createBorderSide(context, width: 10),
        )),
        child: Column(
          children: [
            ///订单号
            orderNumTopWidget(num: model.ordersn ?? "", state: state),
            SizedBox(
              height: 15,
            ),

            ///订单信息
            model.goodsOrderType == 1
                ? orderInfoBuyWidget(
                    image: model.thumb ?? "",
                    title: model.goodsTitle ?? "",
                    type: model.nickname ?? "",
                    price: model.goodsOrderType == 1
                        ? model.buyersPrice ?? ""
                        : model.sellerPrice ?? "")
                : orderInfoSellWidget(
                    image: model.thumb ?? "",
                    id: model.buyersMemberCode ?? "",
                    title: model.goodsTitle ?? "",
                    type: model.nickname ?? "",
                    buyPrice: model.buyersPrice ?? "",
                    sellPrice: model.sellerPrice ?? ""),
            SizedBox(
              height: 12,
            ),

            ///订单价格
            cancelPriceWidget(
                time: model.placeTime ?? "",
                prcie: model.goodsOrderType == 1
                    ? model.buyersPrice ?? ""
                    : model.sellerPrice ?? ""),
          ],
        ),
      ),
    );
  }

  ///订单号
  Widget orderNumTopWidget({required String num, required String state}) {
    return Container(
      child: Row(
        children: [
          Text(
            "订单编号",
            style: TextStyle(fontSize: 12, color: Global.kTheme.inputHint1),
          ),
          SizedBox(
            width: 10,
          ),
          Text(
            num,
            style: TextStyle(fontSize: 12, color: Global.kTheme.inputHint1),
          ),
          Spacer(),
          Padding(
            padding: const EdgeInsets.only(top: 3),
            child: Text(
              state,
              style: TextStyle(fontSize: 12, color: Global.kTheme.inputHint1),
            ),
          ),
        ],
      ),
    );
  }

  ///买单订单信息
  Widget orderInfoBuyWidget(
      {required String image,
      required String title,
      required String type,
      required String price}) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: LoadImage(
              image,
              width: 80,
              height: 80,
              fit: BoxFit.fitHeight,
            )),
        SizedBox(
          width: 13,
        ),
        Expanded(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: 2,
              ),
              Text(
                title,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    fontSize: 14,
                    color: Global.kTheme.textPrimary0,
                    fontFamily: Global.mySemiboldFont),
              ),
              SizedBox(
                height: 5,
              ),
              Text(
                type,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    fontSize: 12,
                    color: Global.kTheme.inputHint1,
                    fontFamily: Global.mySemiboldFont),
              ),
              SizedBox(
                height: 12,
              ),
              Text(
                "¥$price",
                style: TextStyle(
                    fontSize: 12,
                    color: Global.kTheme.textPrimary0,
                    fontFamily: Global.myDINFont),
              ),
            ],
          ),
        )
      ],
    );
  }

  ///卖单订单信息
  Widget orderInfoSellWidget(
      {required String image,
      required String id,
      required String title,
      required String type,
      required String buyPrice,
      required String sellPrice}) {
    //状态 1待付款 2(买)已完成 3代卖中 4(卖)已完成 5订单已超时 6已取消
    bool isShow = false;
    if (widget.model.status == 4) {
      isShow = true;
    }

    return Row(
      children: [
        ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: LoadImage(
              image,
              width: 80,
              height: 80,
              fit: BoxFit.fitHeight,
            )),
        SizedBox(
          width: 13,
        ),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: 1,
              ),
              Text(
                title,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    fontSize: 14,
                    color: Global.kTheme.textPrimary0,
                    fontFamily: Global.mySemiboldFont),
              ),
              SizedBox(
                height: 2,
              ),
              Text(
                type,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    fontSize: 12,
                    color: Global.kTheme.inputHint1,
                    fontFamily: Global.mySemiboldFont),
              ),
              SizedBox(
                height: 2,
              ),
              Text(
                "买家ID $id",
                style: TextStyle(
                    fontSize: 12,
                    color: Global.kTheme.inputHint1,
                    fontFamily: Global.mySemiboldFont),
              ),
              SizedBox(
                height: 2,
              ),
              Row(
                children: [
                  Visibility(
                    visible: isShow,
                    child: Text.rich(TextSpan(children: [
                      TextSpan(
                        text: "买入价格 ",
                        style: TextStyle(
                            fontSize: 12,
                            color: Global.kTheme.inputHint1,
                            fontFamily: Global.mySemiboldFont),
                      ),
                      TextSpan(
                        text: "¥$buyPrice",
                        style: TextStyle(
                            fontSize: 12,
                            color: Global.kTheme.textPrimary0,
                            fontFamily: Global.myDINFont),
                      ),
                    ])),
                  ),
                  SizedBox(
                    width: 10,
                  ),
                  Text.rich(TextSpan(children: [
                    TextSpan(
                      text: "卖出价格 ",
                      style: TextStyle(
                          fontSize: 12,
                          color: Global.kTheme.inputHint1,
                          fontFamily: Global.mySemiboldFont),
                    ),
                    TextSpan(
                      text: "¥$sellPrice",
                      style: TextStyle(
                          fontSize: 12,
                          color: Global.kTheme.textPrimary0,
                          fontFamily: Global.myDINFont),
                    ),
                  ])),
                ],
              )
            ],
          ),
        )
      ],
    );
  }

  ///下单时间
  Widget orderPriceWidget(
      {required String time,
      required String prcie,
      required int goodsOrderType}) {
    return Row(
      children: [
        Text(
          "下单时间:",
          style: TextStyle(fontSize: 12, color: Global.kTheme.inputHint1),
        ),
        Text(
          time,
          style: TextStyle(fontSize: 12, color: Global.kTheme.inputHint1),
        ),
        Spacer(),
        Text(
          goodsOrderType == 1 ? "实付" : "实收",
          style: TextStyle(
              fontSize: 13,
              color: Global.kTheme.inputHint1,
              fontFamily: Global.mySemiboldFont),
        ),
        SizedBox(
          width: 2,
        ),
        Text(
          prcie,
          style: TextStyle(
              fontSize: 14,
              color: Color(0xFFDC241C),
              fontFamily: Global.myDINFont),
        ),
      ],
    );
  }

  ///取消时间
  Widget cancelPriceWidget({required String time, required String prcie}) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text(
          widget.model.status == 5 ? "超时时间:" : "取消时间:",
          style: TextStyle(fontSize: 12, color: Global.kTheme.inputHint1),
        ),
        Text(
          time,
          style: TextStyle(
              fontSize: 12, height: 1.5, color: Global.kTheme.inputHint1),
        ),
      ],
    );
  }

  ///倒计时
  Widget orderCountdownWidget(String time) {
    return Row(
      children: [
        Spacer(),
        Text(
          time,
          style: TextStyle(
              fontSize: 12,
              color: Global.kTheme.textPrimary11,
              fontFamily: Global.mySemiboldFont),
        ),
      ],
    );
  }

  ///付款按钮
  Widget orderPaymentWidget() {
    return Row(
      children: [
        Spacer(),
        InkWell(
          onTap: () async {
            EasyLoading.show(status: "加载中");
            try {
              await ServiceRepository.cancelOrder(widget.model.id.toString());
              EasyLoading.showToast("取消成功");
              widget.onPressed();
            } catch (e, s) {
              EasyLoading.showToast(http.setError(e, s));
            }
          },
          child: Container(
            height: 28,
            padding: EdgeInsets.symmetric(horizontal: 21, vertical: 5),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(14),
              border: Border.all(color: Global.kTheme.inputHint1, width: 1),
            ),
            child: Text(
              "取消订单",
              style: TextStyle(
                fontSize: 12,
                color: Global.kTheme.inputHint1,
              ),
            ),
          ),
        ),
        SizedBox(
          width: 10,
        ),
        InkWell(
          onTap: () async {
            int type = -1;
            if (article?.value == "true" && alArticle?.value == "true") {
              type = await showDialog(
                  context: context,
                  builder: (context) {
                    return new SimpleDialog(
                      title: Text("选择支付方式"),
                      children: [
                        new SimpleDialogOption(
                          child: payItem(
                            icon: "icon_wx",
                            title: "微信",
                            describe: "选择微信支付",
                          ),
                          onPressed: () {
                            Navigator.of(context).pop(2);
                          },
                        ),
                        new SimpleDialogOption(
                          child: payItem(
                            icon: "icon_zfb",
                            title: "支付宝",
                            describe: "选择支付宝支付",
                          ),
                          onPressed: () {
                            Navigator.of(context).pop(1);
                          },
                        ),
                      ],
                    );
                  });
            } else {
              if (article?.value == "true") {
                type = 2;
              } else if (alArticle?.value == "true") {
                type = 1;
              } else {
                type = -1;
              }
            }
            if ((alArticle?.value == "false" &&
                article?.value == "false")|| type == -1) {
              EasyLoading.showToast("支付通道已关闭");
              return;
            }
            EasyLoading.show(status: "加载中");
            try {
              if (type == 1) {
                dynamic model;
                model = await ServiceRepository.goodsPay3(
                    id: widget.model.id.toString());
//                toAlipay(model);
                toWebAipay(model);

              } else {
                dynamic wxData = await ServiceRepository.goodsWXPay(
                    id: widget.model.id.toString());
                toWXPay(wxData);
              }
            } catch (e, s) {
              EasyLoading.showToast(http.setError(e, s));
            }
          },
          child: Container(
            height: 28,
            padding: EdgeInsets.symmetric(horizontal: 21, vertical: 5),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(14),
              border: Border.all(color: Global.kTheme.textPrimary11, width: 1),
            ),
            child: Text(
              "立即付款",
              style: TextStyle(
                fontSize: 12,
                color: Global.kTheme.textPrimary11,
              ),
            ),
          ),
        )
      ],
    );
  }

  void toWebAipay(dynamic model) async{
    if(model["body"]!=null && model["body"]["pay_url"]!=null){
      var _url= model["body"]["pay_url"];
      if (!await launch(_url)) throw 'Could not launch $_url';
      EasyLoading.dismiss();

      await showDialog(
          context: context,
          builder: (context) {
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.all(30),
              child: SizedBox(
                width: 200,
                height: 220,
                child: Container(
                  padding: EdgeInsets.all(30),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius:
                      BorderRadius.all(Radius.circular(10))),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Icon(Icons.offline_pin_rounded,size: 40,color: Colors.green,),
                      SizedBox(
                        height: 10,
                      ),
                      Text(
                        "支付完成",
                        style: TextStyle(
                          fontSize: 18,
                          color: Global.kTheme.textPrimary6,
                          fontFamily: Global.mySemiboldFont,
                        ),
                      ),

                      SizedBox(
                        height: 10,
                      ),

                      SizedBox(
                        height: 10,
                      ),
                      MyButton(
                          minHeight: 40,
                          text: "完成",
                          fontSize: 17,
                          textColor: Global.kTheme.textPrimary5,
                          backgroundColor:
                          Global.kTheme.colorPrimary,
                          onPressed: () {
                            Navigator.of(Get.context!)
                              ..pop();
                            widget.onPressed();
                          })
                    ],
                  ),
                ),
              ),
            );
          });
    }
  }

  void toAlipay(SpecialCastModel model) async {
    print("支付中----");
    //检测是否安装支付宝
    var result = await tobias.isAliPayInstalled();

    if (!result) {
      return EasyLoading.showToast('请安装支付宝');
    }

    if (result) {
      //去支付
      //orderInfo为后台返回的orderInfo
      var payResult = await tobias.aliPay(model.body ?? "");

      if (payResult['result'] != null) {
        if (payResult['resultStatus'].toString() == "9000") {
          EasyLoading.showToast('支付成功');
          widget.onPressed();
        } else {
          EasyLoading.showToast('支付失败');
        }
      }
    }
  }

  void toWXPay(dynamic model) async {
    print("支付中----");
    await fluwx.registerWxApi(
        appId: "wx0f7153ca682343e0",
        universalLink: "https://www.com.example.limaiwl/app/");

    var result = await fluwx.isWeChatInstalled;
    if (!result) {
      return EasyLoading.showToast('请安装微信');
    }

    if (result) {
      //去支付
      //orderInfo为后台返回的orderInfo
      // 将下面这些参数替换成后台返回的即可
      var payRes = await fluwx.payWithWeChat(
        appId: model["body"]["appid"],
        partnerId: model["body"]["partnerid"],
        prepayId: model["body"]["prepayid"],
        packageValue: model["body"]["package"],
        nonceStr: model["body"]["noncestr"],
        timeStamp: model["body"]["timestamp"],
        sign: model["body"]["sign"],
      );

      // 支付回调
      // 一般情况下打开微信支付闪退，errCode为 -1 ，多半是包名、签名和在微信开放平台创建时的配置不一致。
      // 监听支付结果
      if (testSubscription != null) {
        testSubscription?.cancel();
      }
      testSubscription = fluwx.weChatResponseEventHandler.listen((event) async {
        print(event.errCode);
        // 支付成功
        if (event.errCode == 0) {
          EasyLoading.showToast('支付成功');
          widget.onPressed();
        } else {
          // 关闭弹窗
          EasyLoading.showToast('支付失败');
        }
      });
    }
  }

  //时间转换 将秒转换为小时分钟
  String _durationTransform(int seconds) {
    var d = Duration(seconds: seconds);
    List<String> parts = d.toString().split(':');
    return '${parts[0]}小时${parts[1]}分${double.parse(parts[2]).truncate()}秒';
  }

  Widget payItem({
    String? icon,
    String? title,
    String? describe,
  }) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 14),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          LoadImage(
            icon!,
            width: 28,
            height: 28,
          ),
          SizedBox(
            width: 10,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                title!,
                style: TextStyle(
                    fontSize: 14,
                    color: Global.kTheme.textPrimary6,
                    fontFamily: Global.mySemiboldFont),
              ),
              Text(
                describe!,
                style: TextStyle(fontSize: 12, color: Color(0xFFA0A0A0)),
              ),
            ],
          ),
          Spacer(),
          // Icon(
          //   (isSelect ?? false)
          //       ? Icons.check_circle
          //       : Icons.radio_button_unchecked_rounded,
          //   size: 18,
          // ),
        ],
      ),
    );
  }

  void getConfigNameDetail(String name) async {
    try {
      List list = await ServiceRepository.getConfigNameDetail(name);
      list.forEach((element) {
        if (element.name.toString().trim() == name) {
          article = element;
        }
      });
    } catch (e, s) {}
    setState(() {});
  }

  void getConfigNameDetailAli(String name) async {
    try {
      List list = await ServiceRepository.getConfigNameDetail(name);
      list.forEach((element) {
        if (element.name.toString().trim() == name) {
          alArticle = element;
        }
      });
    } catch (e, s) {}
    setState(() {});
  }
}
